package com.syni.mdd.yhd.common.all.service.impl;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsDxGroupBuyUseDao;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.UserGroupBuyUseRpDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupBuy.GroupBuyUseReDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusinessCoupon;
import com.syni.mdd.yhd.common.all.entity.BmsDxGroupBuy;
import com.syni.mdd.yhd.common.all.entity.BmsDxGroupBuyUse;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsFullCoupon;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.record.ReOrderLog;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrOrderLogService;
import com.syni.mdd.yhd.common.all.utils.OrderUtils;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
@Log4j2
public class BmsDxGroupBuyUseImpl extends BaseService<BmsDxGroupBuyUse, Integer> implements BmsDxGroupBuyUseService {

    @Autowired
    BmsDxGroupBuyUseDao bmsDxGroupBuyUseDao;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsThirdCodeService bmsThirdCodeService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    BmsDrOrderLogService bmsDrOrderLogService;

    @Autowired
    BmsVerRecordService bmsVerRecordService;

    @Autowired
    ImgPrefixService imgPrefixService;

    @Override
    public BmsDxGroupBuyUseDao getBaseDao() {
        return bmsDxGroupBuyUseDao;
    }

    @Override
    public List<BmsDxGroupBuyUse> getGroupByCode(Integer orderId,Integer status) {
        return bmsDxGroupBuyUseDao.findByOrderIdAndStatus(orderId,status);
    }

    public List<BmsDxGroupBuyUse> getGroupByCodeOrderNoUse(Integer orderId) {
        Set<Integer> orderIds = new HashSet<>();
        orderIds.add(orderId);
        return bmsDxGroupBuyUseDao.findByGroupCodeByMySort(orderIds);
    }

    @Override
    public Map<Integer,List<BmsDxGroupBuyUse>> getGroupByCode(Set ids) {
        Map<Integer,List<BmsDxGroupBuyUse>> resultMap = new HashMap<>();
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseDao.findByGroupCodeByMySort(ids);
        if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                if(!resultMap.containsKey(bmsDxGroupBuyUse.getOrderId())){
                    resultMap.put(bmsDxGroupBuyUse.getOrderId(),new ArrayList<>());
                }
                resultMap.get(bmsDxGroupBuyUse.getOrderId()).add(bmsDxGroupBuyUse);
            }
        }
        return resultMap;
    }

    @Override
    public Double countGroupOrderTotal(Integer businessId, Set useStatus) {
        return bmsDxGroupBuyUseDao.countGroupBuyUse(businessId,useStatus);
    }

    @Override
    public Double countGroupOrderTotal(Integer businessId, Integer useStatus) {
        Set statuses = new HashSet();
        statuses.add(useStatus);
        return bmsDxGroupBuyUseDao.countGroupBuyUse(businessId,statuses);
    }

    /**
     * @Description 统计数
     * @Param: [businessId, status, startTime, endTime]
     * @return: java.lang.Integer
     * @Author: cfx
     * @Date: 2019/7/31
     */
    @Override
    public Integer countGroupBuyUseCountByTime(Integer businessId,Set status,
                                               String startTime,String endTime) {
        Set<Integer> businessIds = new HashSet<>();
        businessIds.add(businessId);
        return bmsDxGroupBuyUseDao.countGroupBuyUseCountByTime(businessIds,status,startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    @Override
    public Integer countGroupBuyUseCountByTime(Set businessIds,Set status,
                                               String startTime,String endTime) {
        return bmsDxGroupBuyUseDao.countGroupBuyUseCountByTime(businessIds,status,startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    @Override
    public Map<Integer,Integer> countGroupBuyUseCountByBusinessIds(Set businessIds,String startTimes,String endTimes) {
        Map<Integer,Integer> resultMap = new HashMap<>();
        Set<Integer> useStatuses = new HashSet<>();
        useStatuses.add(Constants.GROUP_ALREADY_USE);
        List<Map<String,Object>> result =  bmsDxGroupBuyUseDao.countGroupBuyUseCountByBusinessIds(businessIds,useStatuses,startTimes,endTimes);
        if(CollectionUtils.isNotEmpty(result)){
            result.forEach(obj -> {
                resultMap.put(Integer.parseInt(obj.get("businessId").toString()),Integer.parseInt(obj.get("num").toString()));
            });
        }
        return resultMap;
    }

    /**
     * @Description 统计金额
     * @Param: [businessId, status, startTime, endTime]
     * @return: java.lang.Integer
     * @Author: cfx
     * @Date: 2019/7/31
     */
    @Override
    public Double countGroupBuyUseSumByTime(Integer businessId, Set status, String startTime, String endTime) {
        Set<Integer> businessIds = new HashSet<>();
        businessIds.add(businessId);
        return bmsDxGroupBuyUseDao.countGroupBuyUseSumByTime(businessIds,status,startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    @Override
    public Double countGroupBuyUseSumByTime(Set businessId, Set status, String startTime, String endTime) {
        return bmsDxGroupBuyUseDao.countGroupBuyUseSumByTime(businessId,status,startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    /**
     * @Description 获取团购券核销张数信息
     * @Author: cfx
     * @Date: 2019/7/31
     */
    @Override
    public List<Map<String,Object>> getGroupBuyNumMap(Set orderIds) {
        return bmsDxGroupBuyUseDao.countOnceOrderUserNum(orderIds, Constants.GROUP_ALREADY_USE);
    }

    /**
     * @Description 用户获取我的卡券包
     * @Author: cfx
     * @Date: 2019/7/31
     */
    public Map<String,Object> userGetGroupBuyUse(GroupBuyUseReDto groupBuyUseReDto) {
        //查看我买了哪些团购
        List<UserGroupBuyUseRpDto> buyUseRpDtos = new LinkedList<>();
        Map<String,Object> conditionMap = new HashMap<>();
        if(groupBuyUseReDto.getOrderId() != null || groupBuyUseReDto.getSearchGroupUseCode() != null){
            if(groupBuyUseReDto.getOrderId() != null) {
                conditionMap.put("orderId", groupBuyUseReDto.getOrderId());
            }
            if(groupBuyUseReDto.getSearchGroupUseCode() != null){
                conditionMap.put("groupBuyCode",groupBuyUseReDto.getSearchGroupUseCode());
            }
        }else {
            //根据用户id寻找
            conditionMap.put("userId",Integer.parseInt(groupBuyUseReDto.getUserId()));
            //查询用户未使用的团购券码
            Map<String,Object> conditionForUse = new HashMap<>();
            conditionForUse.put("userId",Integer.parseInt(groupBuyUseReDto.getUserId()));
            conditionForUse.put("status",Constants.GROUP_NO_USE);
            Map<String,Object> conditionForUseGroup = new HashMap<>();
            conditionForUseGroup.put("orderId_GB",Integer.parseInt(groupBuyUseReDto.getUserId()));
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseDao.
                    findAll(new SpecificationUtils(conditionForUse,conditionForUseGroup));
            if(!(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0)){
                return ResultMapHelper.success(buyUseRpDtos, ResultMsg.MSG_GET_SUCCESS);
            }
            Set<Integer> groupUseIds = new HashSet<>();
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                groupUseIds.add(bmsDxGroupBuyUse.getId());
            }
            conditionMap.put("id_IN",groupUseIds);
        }
        Map<String,Object> groupMap = new HashMap<>();
        groupMap.put("orderId_GB",Constants.COMMON_FLAG_FALSE_INT);
        Pageable pageable = BmsCommonService.getPageable(groupBuyUseReDto.getPageNum(),groupBuyUseReDto.getPageSize(),
                Sort.Direction.DESC,"newTime");
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseDao.
                findAll(new SpecificationUtils(conditionMap,groupMap),pageable).getContent();

        Set<Integer> groupBuyIds = new HashSet<>();
        Set<Integer> orderIds = new HashSet<>();
        if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                //记录
                groupBuyIds.add(bmsDxGroupBuyUse.getGroupBuyId());
                orderIds.add(bmsDxGroupBuyUse.getOrderId());
                //克隆
                UserGroupBuyUseRpDto userGroupBuyUseRpDto = new UserGroupBuyUseRpDto();
                BeanUtils.copyProperties(bmsDxGroupBuyUse,userGroupBuyUseRpDto);
                buyUseRpDtos.add(userGroupBuyUseRpDto);
            }
            //Map<Integer, BmsDxGroupBuy> bmsDxGroupBuyMap =  bmsDxGroupBuyService.getGroupBuyById(groupBuyIds);
            Map<Integer,List<BmsDxGroupBuyUse>> groupBuyUseMap = bmsDxGroupBuyUseService.getGroupByCode(orderIds);
            Map<Integer, BmsDxOrder> bmsDxOrderMap = bmsDxOrderService.getOrderMap(orderIds);
            for(UserGroupBuyUseRpDto userGroupBuyUseRpDto : buyUseRpDtos){
                if(bmsDxOrderMap.containsKey(userGroupBuyUseRpDto.getOrderId())){
                    BmsDxOrder bmsDxOrder = bmsDxOrderMap.get(userGroupBuyUseRpDto.getOrderId());
                    BeanUtils.copyProperties(bmsDxOrder,userGroupBuyUseRpDto);
                    if(userGroupBuyUseRpDto.getBmsDxGroupBuy() != null){
                        //优化富文本字段
                        //userGroupBuyUseRpDto.getBmsDxGroupBuy().setTextContent(null);
                        userGroupBuyUseRpDto.getBmsDxGroupBuy().setGroupContent(null);
                    }
                }
                /*if(bmsDxGroupBuyMap.containsKey(userGroupBuyUseRpDto.getGroupBuyId())){
                    userGroupBuyUseRpDto.setBmsDxGroupBuy(bmsDxGroupBuyMap.get(userGroupBuyUseRpDto.getGroupBuyId()));
                }*/
                if(groupBuyUseMap.containsKey(userGroupBuyUseRpDto.getOrderId())){
                    userGroupBuyUseRpDto.setBmsDxGroupBuyUse(groupBuyUseMap.get(userGroupBuyUseRpDto.getOrderId()));
                }
            }
        }
        //处理图片
        buyUseRpDtos.forEach(v->{
            imgPrefixService.pushSpliceField(v.getBmsDxGroupBuy(),"groupImg","detailImg","groupPhotos");
            imgPrefixService.pushSpliceField(v.getBmsDxGroupBuy().getBmsBusiness(),"logoUrl");
            imgPrefixService.pushSpliceField(v.getBmsDxGroupBuy().getBmsBusiness().getOtherGroupBuys(),"groupImg","detailImg");
        });
        if(CollectionUtils.isNotEmpty(buyUseRpDtos)){
            for(UserGroupBuyUseRpDto userGroupBuyUseRpDto : buyUseRpDtos ) {
                postHandleQrCodeText(userGroupBuyUseRpDto.getBmsDxGroupBuyUse());
            }
            for(UserGroupBuyUseRpDto userGroupBuyUseRpDto : buyUseRpDtos ) {
                userGroupBuyUseRpDto.setQrCodeText(userGroupBuyUseRpDto.getBmsDxGroupBuyUse().get(0).getQrCodeText());
            }
        }
        return ResultMapHelper.success(buyUseRpDtos, ResultMsg.MSG_GET_SUCCESS);
    }

    public void postHandleQrCodeText(List<BmsDxGroupBuyUse> bmsDxGroupBuyUses) {
        if(CollectionUtils.isNotEmpty(bmsDxGroupBuyUses)){
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                String qrCodeText = String.format("Syni_MDD_verNo=%s",bmsDxGroupBuyUse.getGroupBuyCode());
                bmsDxGroupBuyUse.setQrCodeText(qrCodeText);
            }
        }
    }

    /**
     * @Description: 统计用户核销的团购券次数
     * @Param userId
     * @return Integer
     * @Author: cfx
     * @Date: 2019/9/2
     */
    @Override
    public Integer countUserUseGroupBuyNum(Integer userId) {
        return bmsDxGroupBuyUseDao.countUserUseGroupBuyNum(userId);
    }

    /**
     * @Description: 统计用户购买某张券的次数
     * @Param userId
     * @return Integer
     * @Author: cfx
     * @Date: 2019/9/2
     */
    @Override
    public Integer getUserBuyNum(Integer userId, Integer id) {
        return bmsDxGroupBuyUseDao.countUserBuyGroupBuyNum(userId,id);
    }

    @Override
    public List<Map<String,Object>> countUserReceGroupBuy(Set userReceIds) {
        List<Map<String,Object>> resultMap = new ArrayList<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("fullCouponId_IN",userReceIds);
        conditionMap.put("orderType",Constants.GROUP_BUY_ORDER_TYPE);
        List<BmsDxOrder> bmsDxOrders = bmsDxOrderService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> orderIds = bmsDxOrders.stream().map(BmsDxOrder::getId).collect(Collectors.toSet());
            resultMap = bmsDxGroupBuyUseDao.countActivityGroupBuy(orderIds);
        }
        return resultMap;
    }

    @Override
    public ReOrderLog generateGroupUse(ReOrderLog orderLog,BmsDxOrder bmsDxOrder,Date nowTime) {
        orderLog.setGroupCodeStart(nowTime);
        List<String> groupBuyCodes = new ArrayList<>();
        Integer groupBuyId = bmsDxOrder.getBmsGroupBuyId();
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
        //拿出对应的特特勒团购记录
        //拿出对应的code
        LinkedList<String> codes = new LinkedList<>();
        if(bmsDxGroupBuy.getGroupType() == null
                || bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_GEN
                || bmsDxGroupBuy.getGroupType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
            codes.addAll(findCanUseCode(bmsDxGroupBuy,bmsDxOrder.getGroupBuyNum()));
        }else if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
            codes.addAll(bmsThirdCodeService.findCanUseCode(bmsDxOrder));
        }
        if(bmsDxGroupBuy != null) {
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = new ArrayList<>();
            for (int ii = 0; ii < bmsDxOrder.getGroupBuyNum(); ii++) {
                BmsDxGroupBuyUse bmsDxGroupBuyUse = new BmsDxGroupBuyUse();
                bmsDxGroupBuyUse.setNewTime(nowTime);
                //补救措施
                if(!(codes.size() > 0)){
                    codes.add(OrderUtils.getGroupBuyPayNo(true));
                }
                bmsDxGroupBuyUse.setGroupBuyCode(codes.poll());
                bmsDxGroupBuyUse.setOrderId(bmsDxOrder.getId());
                bmsDxGroupBuyUse.setUserId(bmsDxOrder.getBmsUserId());
                bmsDxGroupBuyUse.setStatus(Constants.COMMON_FLAG_FALSE_INT);
                if(bmsDxGroupBuy.getIsBusinessConsume() != null && bmsDxGroupBuy.getIsBusinessConsume() == Constants.COMMON_FLAG_FALSE_INT){
                    bmsDxGroupBuyUse.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                    bmsDxGroupBuyUse.setUseTime(nowTime);
                }
                bmsDxGroupBuyUse.setGroupBuyId(bmsDxOrder.getBmsGroupBuyId());
                bmsDxGroupBuyUse.setBusinessId(bmsDxOrder.getBmsBusinessId());
                Double settleMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getGroupPrice(), Constants.SEETLE_LINES);
                Double onceShopMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getGroupPrice(), Constants.SEETLE_LINES);
                Double groupBuyPrice = bmsDxOrder.getBmsDxGroupBuy().getGroupPrice();
                Double gbuyActualConsum = ArithUtil.round(ArithUtil.div(bmsDxOrder.getActualConsum(), bmsDxOrder.getGroupBuyNum()), 2);
                if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
                    settleMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getCostPrice(), Constants.SEETLE_LINES);
                    onceShopMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getCostPrice(), Constants.SEETLE_LINES);
                    groupBuyPrice = gbuyActualConsum;
                    //gbuyActualConsum = ArithUtil.round(ArithUtil.div(bmsDxGroupBuy.getCostPrice(), bmsDxOrder.getGroupBuyNum()), 2);
                }
                Double discountMoney = 0d;
                if (bmsDxOrder.getFullCouponId() != null) {
                    BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponService.getBaseDao().findByIdAndStatus(bmsDxOrder.getFullCouponId(), Constants.COMMON_FLAG_TRUE_INT);
                    if (bmsUserReceCoupon != null) {
                        BmsFullCoupon bmsFullCoupon = bmsUserReceCoupon.getBmsFullCoupon();
                        BmsBusinessCoupon businessCoupon = bmsUserReceCoupon.getBmsBusinessCoupon();
                        //满减额度
                        Double reduction = 0d;
                        if (bmsFullCoupon != null) {
                            String[] fullRules = bmsUserReceCoupon.getBmsFullCoupon().getFullRule().split("_");
                            reduction = Double.parseDouble(fullRules[1]);
                        } else if (businessCoupon != null) {
                            String content = businessCoupon.getCouponContent();
                            Map<String, Object> contentMap = JSON.parseObject(content);
                            //触发金额
                            reduction = Double.parseDouble(contentMap.get("amount").toString());
                        }
                        //单张券的补贴
                        Double singleSubsidies = ArithUtil.round(ArithUtil.div(reduction, bmsDxOrder.getGroupBuyNum()), 2);
                        discountMoney = singleSubsidies;
                        //真正分账的钱
                        settleMoney = ArithUtil.sub(settleMoney, discountMoney);
                    }
                }
                if (bmsDxOrder.getBackCardId() != null) {
                    Double useBackMoney = bmsDxOrder.getUseCardMoney();
                    //单张券的补贴
                    Double singleSubsidies = ArithUtil.round(ArithUtil.div(useBackMoney, bmsDxOrder.getGroupBuyNum()), 2);
                    bmsDxGroupBuyUse.setBackCacdMoney(singleSubsidies);
                    discountMoney = ArithUtil.add(discountMoney, singleSubsidies);
                    //真正分账的钱
                    //settleMoney = ArithUtil.sub(settleMoney, discountMoney);
                }
                if (settleMoney > 0d) {
                    settleMoney = 0d;
                }
                bmsDxGroupBuyUse.setDiscountMoney(discountMoney);
                bmsDxGroupBuyUse.setSettleMoney(settleMoney);
                bmsDxGroupBuyUse.setOnceShopMoney(onceShopMoney);
                bmsDxGroupBuyUse.setGroupBuyPrice(groupBuyPrice);
                bmsDxGroupBuyUse.setGbuyActualConsum(gbuyActualConsum);
                //如果是特特乐团购
                if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                    bmsDxGroupBuyUse.setStatus(Constants.GROUP_ALREADY_USE);
                    bmsDxGroupBuyUse.setUseTime(nowTime);
                    bmsDxGroupBuyUse.setUseManId(bmsUserBusinessAuthService.findBusinessManager(bmsDxGroupBuy.getBusinessId()));
                    bmsDxGroupBuyUse.setUseManRole(Constants.BUSINESS_ROLE_ID);
                    bmsDxGroupBuyUse.setNickName(Constants.BUSINESS_NAME);
                    bmsDxGroupBuyUse.setUseWay(USE_WAY_IN_CODE);
                }
                bmsDxGroupBuyUses.add(bmsDxGroupBuyUse);
                groupBuyCodes.add(bmsDxGroupBuyUse.getGroupBuyCode());
            }
            if(bmsDxGroupBuyUses.size() > 0){
                bmsDxGroupBuyUseService.getBaseDao().saveAll(bmsDxGroupBuyUses);
                //添加一份核销记录到核销记录表
                bmsVerRecordService.addRecordByBuyQuan(bmsDxGroupBuyUses);
            }
        }
        orderLog.setGroupCodes(JSON.toJSONString(groupBuyCodes));
        orderLog.setGroupCodeEnd(new Date());
        return orderLog;
    }

    public void generateGroupUse_V2(BmsDxOrder bmsDxOrder,Date nowTime) {
        List<String> groupBuyCodes = new ArrayList<>();
        Integer groupBuyId = bmsDxOrder.getBmsGroupBuyId();
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
        //拿出对应的特特勒团购记录
        //拿出对应的code
        LinkedList<String> codes = new LinkedList<>();
        if(bmsDxGroupBuy.getGroupType() == null
                || bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_GEN
                || bmsDxGroupBuy.getGroupType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
            codes.addAll(findCanUseCode(bmsDxGroupBuy,bmsDxOrder.getGroupBuyNum()));
        }else if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
            codes.addAll(bmsThirdCodeService.findCanUseCode(bmsDxOrder));
        }
        if(bmsDxGroupBuy != null) {
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = new ArrayList<>();
            for (int ii = 0; ii < bmsDxOrder.getGroupBuyNum(); ii++) {
                BmsDxGroupBuyUse bmsDxGroupBuyUse = new BmsDxGroupBuyUse();
                bmsDxGroupBuyUse.setNewTime(nowTime);
                //补救措施
                if(!(codes.size() > 0)){
                    codes.add(OrderUtils.getGroupBuyPayNo(true));
                }
                bmsDxGroupBuyUse.setGroupBuyCode(codes.poll());
                bmsDxGroupBuyUse.setOrderId(bmsDxOrder.getId());
                bmsDxGroupBuyUse.setUserId(bmsDxOrder.getBmsUserId());
                bmsDxGroupBuyUse.setStatus(Constants.COMMON_FLAG_FALSE_INT);
                bmsDxGroupBuyUse.setGroupBuyId(bmsDxOrder.getBmsGroupBuyId());
                bmsDxGroupBuyUse.setBusinessId(bmsDxOrder.getBmsBusinessId());
                Double settleMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getGroupPrice(), Constants.SEETLE_LINES);
                Double onceShopMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getGroupPrice(), Constants.SEETLE_LINES);
                Double groupBuyPrice = bmsDxOrder.getBmsDxGroupBuy().getGroupPrice();
                Double gbuyActualConsum = ArithUtil.round(ArithUtil.div(bmsDxOrder.getActualConsum(), bmsDxOrder.getGroupBuyNum()), 2);
                if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
                    settleMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getCostPrice(), Constants.SEETLE_LINES);
                    onceShopMoney = ArithUtil.mul(bmsDxOrder.getBmsDxGroupBuy().getCostPrice(), Constants.SEETLE_LINES);
                    groupBuyPrice = gbuyActualConsum;
                    //gbuyActualConsum = ArithUtil.round(ArithUtil.div(bmsDxGroupBuy.getCostPrice(), bmsDxOrder.getGroupBuyNum()), 2);
                }
                Double discountMoney = 0d;
                if (bmsDxOrder.getFullCouponId() != null) {
                    BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponService.getBaseDao().findByIdAndStatus(bmsDxOrder.getFullCouponId(), Constants.COMMON_FLAG_TRUE_INT);
                    if (bmsUserReceCoupon != null) {
                        BmsFullCoupon bmsFullCoupon = bmsUserReceCoupon.getBmsFullCoupon();
                        BmsBusinessCoupon businessCoupon = bmsUserReceCoupon.getBmsBusinessCoupon();
                        //满减额度
                        Double reduction = 0d;
                        if (bmsFullCoupon != null) {
                            String[] fullRules = bmsUserReceCoupon.getBmsFullCoupon().getFullRule().split("_");
                            reduction = Double.parseDouble(fullRules[1]);
                        } else if (businessCoupon != null) {
                            String content = businessCoupon.getCouponContent();
                            Map<String, Object> contentMap = JSON.parseObject(content);
                            //触发金额
                            reduction = Double.parseDouble(contentMap.get("amount").toString());
                        }
                        //单张券的补贴
                        Double singleSubsidies = ArithUtil.round(ArithUtil.div(reduction, bmsDxOrder.getGroupBuyNum()), 2);
                        discountMoney = singleSubsidies;
                        //真正分账的钱
                        settleMoney = ArithUtil.sub(settleMoney, discountMoney);
                    }
                }
                if (bmsDxOrder.getBackCardId() != null) {
                    Double useBackMoney = bmsDxOrder.getUseCardMoney();
                    //单张券的补贴
                    Double singleSubsidies = ArithUtil.round(ArithUtil.div(useBackMoney, bmsDxOrder.getGroupBuyNum()), 2);
                    bmsDxGroupBuyUse.setBackCacdMoney(singleSubsidies);
                    discountMoney = ArithUtil.add(discountMoney, singleSubsidies);
                    //真正分账的钱
                    //settleMoney = ArithUtil.sub(settleMoney, discountMoney);
                }
                if (settleMoney > 0d) {
                    settleMoney = 0d;
                }
                bmsDxGroupBuyUse.setDiscountMoney(discountMoney);
                bmsDxGroupBuyUse.setSettleMoney(settleMoney);
                bmsDxGroupBuyUse.setOnceShopMoney(onceShopMoney);
                bmsDxGroupBuyUse.setGroupBuyPrice(groupBuyPrice);
                bmsDxGroupBuyUse.setGbuyActualConsum(gbuyActualConsum);
                //如果是特特乐团购
                if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                    bmsDxGroupBuyUse.setStatus(Constants.GROUP_ALREADY_USE);
                    bmsDxGroupBuyUse.setUseTime(nowTime);
                    bmsDxGroupBuyUse.setUseManId(bmsUserBusinessAuthService.findBusinessManager(bmsDxGroupBuy.getBusinessId()));
                    bmsDxGroupBuyUse.setUseManRole(Constants.BUSINESS_ROLE_ID);
                    bmsDxGroupBuyUse.setNickName(Constants.BUSINESS_NAME);
                    bmsDxGroupBuyUse.setUseWay(USE_WAY_IN_CODE);
                }
                bmsDxGroupBuyUses.add(bmsDxGroupBuyUse);
                groupBuyCodes.add(bmsDxGroupBuyUse.getGroupBuyCode());
            }
            if(bmsDxGroupBuyUses.size() > 0){
                bmsDxGroupBuyUseService.getBaseDao().saveAll(bmsDxGroupBuyUses);
                //添加一份核销记录到核销记录表
                bmsVerRecordService.addRecordByBuyQuan(bmsDxGroupBuyUses);
            }
        }
    }

    private List<String> findCanUseCode(BmsDxGroupBuy bmsDxGroupBuy, Integer groupBuyNum) {
        List<String> codes = new ArrayList<>();
        for(int ii = 0;ii < groupBuyNum;ii++){
            codes.add(OrderUtils.getGroupBuyPayNo(true));
        }
        return codes;
    }

    @Override
    public List<BmsDxGroupBuyUse> getAllVerRecord(Integer orderId) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("orderId",orderId);
        conditionMap.put("status",Constants.GROUP_ALREADY_USE);
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseDao.findAll(new SpecificationUtils(conditionMap));
        return bmsDxGroupBuyUses;
    }

    @Override
    public void countBackCard(BmsDxGroupBuyUse bmsDxGroupBuyUse) {
        Integer orderId = bmsDxGroupBuyUse.getOrderId();
        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findByIdAndIsDelete(orderId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder != null) {
            //查询当前订单是否全部核销完毕
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getAllVerRecord(orderId);
            if(bmsDxOrder.getGroupBuyNum() == bmsDxGroupBuyUses.size()){
                //全部核销完成
                Double backMoney = 0d;
                for(BmsDxGroupBuyUse groupBuyUse : bmsDxGroupBuyUses){
                    backMoney = ArithUtil.add(backMoney,groupBuyUse.getGbuyActualConsum());
                }
                bmsDrOrderLogService.countBackCard(bmsDxOrder,bmsDxGroupBuyUse.getId(),backMoney);
            }
        }
    }

    @Override
    public Integer countRefundIngNum(Integer orderId) {
        Map<String,Object> orderStatusConditionMap = new HashMap<>();
        orderStatusConditionMap.put("orderId",orderId);
        orderStatusConditionMap.put("status",Constants.GROUP_NO_USE);
        orderStatusConditionMap.put("isRefund",Constants.COMMON_FLAG_TRUE_INT);
        orderStatusConditionMap.put("refundResult",Constants.COMMON_FLAG_FALSE_INT);
        return (int)(bmsDxGroupBuyUseService.getBaseDao().count(new SpecificationUtils(orderStatusConditionMap)));
    }

    @Override
    public Integer countRefundNum(Integer orderId) {
        Map<String,Object> orderStatusConditionMap = new HashMap<>();
        orderStatusConditionMap.put("orderId",orderId);
        orderStatusConditionMap.put("status",Constants.GROUP_REFUND_COMPLETE);
        return (int)(bmsDxGroupBuyUseService.getBaseDao().count(new SpecificationUtils(orderStatusConditionMap)));
    }

    @Override
    public Map<String, Object> countMoneyData(Integer orderId, Date verTime) {
        Map<String,Object> moneyData = bmsDxGroupBuyUseDao.countMoneyData(orderId,DateTimeUtils.converDateToInterger(verTime));
        return moneyData;
    }

    @Override
    public BmsDxGroupBuyUse getGroupByCode(String code) {
        return bmsDxGroupBuyUseDao.findByGroupBuyCode(code);
    }

    @Override
    public void addRefundId(List<BmsDxGroupBuyUse> buyUses, String refundId) {
        try {
            if(CollectionUtils.isNotEmpty(buyUses)){
                for(BmsDxGroupBuyUse bmsDxGroupBuyUse : buyUses){
                    RedisTemplateUtils.getRedisTemplate().opsForValue().set(Constants.REDIS_GROUB_USER_REFUND_ID + bmsDxGroupBuyUse.getGroupBuyCode(),refundId);
                }
            }
        }catch (Exception e){
            log.error("addRefundId:",e);
        }

    }

    @Override
    public boolean checkCouponBelongBusiness(Integer businessId, Integer orderId) {
        Optional<BmsDxOrder> bmsDxOrder = bmsDxOrderService.getBaseDao().findById(orderId);
        if(bmsDxOrder.isPresent()){
            return bmsDxOrder.get().getBmsBusinessId().equals(businessId);
        }
        return false;
    }
}
